package com.jsaas.interceptor;

import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.aop.MethodInvocation;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.aop.AnnotationsAuthorizingMethodInterceptor;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.kit.Ret;
import com.jfinal.log.Log;
import com.jsaas.utils.MyUtils;

/**   
* @Title: ShiroInterceptor.java 
* @Package com.jsaas.interceptor 
* @Description: TODO(处理“RequiresAuthentication”、“RequiresGuest”、“RequiresPermissions”、“RequiresRoles”、“RequiresUser” 注解) 
* @author tuozq 
* @date 2017年12月18日 下午4:03:37 
* @version V1.0   
*/
public class ShiroInterceptor extends AnnotationsAuthorizingMethodInterceptor implements Interceptor {
	
	private static final Log log = Log.getLog(ShiroInterceptor.class);
	
	public ShiroInterceptor() {
        getMethodInterceptors();    //用来扩展其他注解
    }
	
	public void intercept(final Invocation inv) {
		// TODO Auto-generated method stub
		try {
			invoke(new MethodInvocation() {
				
				public Object proceed() throws Throwable {
                    inv.invoke();
                    return inv.getReturnValue();
                }
                public Method getMethod() {
                    return inv.getMethod();
                }
 
                public Object[] getArguments() {
                    return inv.getArgs();
                }
 
                public Object getThis() {
                    return inv.getController();
                }
			});
		} catch (Throwable e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			if (e instanceof AuthorizationException) {
                doProcessuUnauthorization(inv.getController());
                AuthorizationException exception = (AuthorizationException)e;
    			log.info("禁止访问:" + exception.getMessage());
            }
		}
	}
 
    /**
     * 未授权处理
     *
     * @param controller controller
     */
    private void doProcessuUnauthorization(Controller controller) {
    	HttpServletRequest request = controller.getRequest();
    	boolean isAjax = MyUtils.isAjax(request);
		if(isAjax){
			controller.renderJson(Ret.fail().set("msg", "权限不足，对不起，您没有访问此操作的权限。"));
		}else{
			String redirctUrl = request.getHeader("referer");
			if (StringUtils.isBlank(redirctUrl)) {
				redirctUrl = request.getRequestURI();
			}
			controller.setAttr("redirctUrl", redirctUrl);
			controller.render("/views/error/403.html");
		}
    }
}
